package com.catazy.wanandroid.common_base.glide

import android.content.Context
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool
import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import com.catazy.wanandroid.common_base.glide.okhttp.OkHttpUrlLoader
import com.catazy.wanandroid.common_base.net.ServiceCreators
import com.catazy.wanandroid.common_base.util.FileUtil
import java.io.InputStream

/**
 * 作者: Tao
 * 日期: 2024/4/10
 * 时间: 11:28
 * 描述: GlideAppModule 设置全局Glide 配置 比如设置缓存图片大小，设置图片格式
 */
@GlideModule
class ImageAppModule : AppGlideModule() {

    override fun applyOptions(context: Context, builder: GlideBuilder) {
//        设置缓存大小为20mb
//        val memoryCacheSizeBytes = 1024 * 1024 * 20 // 20mb
//        builder.setMemoryCache(LruResourceCache(memoryCacheSizeBytes.toLong()))

        // 设置内存缓存大小、图片池大小
        val calculator = MemorySizeCalculator.Builder(context)
            .setMemoryCacheScreens(5.toFloat()) // 设置内存缓存大小
            .setBitmapPoolScreens(5.toFloat()) // 设置图片池大小
            .build()
        builder.setMemoryCache(LruResourceCache(calculator.memoryCacheSize.toLong()))
        builder.setBitmapPool(LruBitmapPool(calculator.bitmapPoolSize.toLong()))

        // 设置磁盘缓存
        if (FileUtil.isExistExternalStore()) {
            // 外部存储
            builder.setDiskCache(ExternalPreferredCacheDiskCacheFactory(context))
        } else {
            // 内部存储
            builder.setDiskCache(InternalCacheDiskCacheFactory(context))
        }
    }

    /**
     * 注册组件
     */
    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        // 设置网络请求组件
        registry.replace(
            GlideUrl::class.java,
            InputStream::class.java,
            OkHttpUrlLoader.Factory(ServiceCreators.httpClient)
        )
    }

    /**
     * 禁用清单解析
     */
    override fun isManifestParsingEnabled(): Boolean {
        return false
    }
}